package com.goodcol.plugin.ui;

import com.goodcol.plugin.tool.Constants;
import com.goodcol.plugin.tool.DeviceTool;
import com.goodcol.plugin.tool.LicenseUtils;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.util.ui.TextTransferable;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

/**
 * LicenseDialog
 *
 * @author 单红宇
 * @date 2024-03-12 16:28:43
 */
public class LicenseDialog extends DialogWrapper {
    private JPanel contentPane;
    private JTextField licenseCode;
    private JLabel regCode;
    private JLabel expireTime;
    private JButton copy;

    public LicenseDialog(Project project) {
        super(project);
        setTitle(Constants.TITLE_INFO);
        this.setOKButtonText("保存授权码");
        init();
        initPanel();
        initEvent();
    }

    private void initPanel() {
        regCode.setText(DeviceTool.getDeviceId());
        licenseCode.setText(LicenseUtils.getLicense());
        String licenseExpTime = LicenseUtils.checkLicense(LicenseUtils.getLicense());
        expireTime.setText(StringUtils.isNotBlank(licenseExpTime) ?
                DateFormatUtils.format(Long.parseLong(licenseExpTime), "yyyy-MM-dd HH:mm:ss") :
                "请输入有效的授权码");
    }

    private void initEvent() {
        copy.addActionListener(e -> {
            CopyPasteManager.getInstance().setContents(new TextTransferable(regCode.getText()));
            Messages.showInfoMessage("Copy Success！", Constants.TITLE_INFO);
        });
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        return this.contentPane;
    }

    @Override
    protected void doOKAction() {
        String licCode = licenseCode.getText();
        String licenseExpTime = LicenseUtils.checkLicense(licCode);
        if (licenseExpTime != null) {
            expireTime.setText(DateFormatUtils.format(Long.parseLong(licenseExpTime), "yyyy-MM-dd HH:mm:ss"));
            if (LicenseUtils.saveLicense(licCode)) {
                this.close(OK_EXIT_CODE);
                Messages.showInfoMessage("授权码验证保存成功", Constants.TITLE_INFO);
            }
        } else {
            expireTime.setText("请输入有效的授权码");
            Messages.showInfoMessage("无效的授权码！", Constants.TITLE_INFO);
        }
    }

}
